<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                xmlns="http://www.fi.muni.cz/internationalaid"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://www.fi.muni.cz/internationalaid
                                    aid.xsd">
    
    <xsl:output method="xml"
                encoding="UTF-8"
                indent="yes"
                omit-xml-declaration="no"
    />
    
    <!-- key for generating distinct country codes (Muenchian grouping) -->
    <xsl:key name="kCountry" match="/aid/country" use="@code"/>
            
    
    <xsl:template match="aid">
        <aid xsi:schemaLocation="http://www.fi.muni.cz/internationalaid aid.xsd">
                        
            <!-- selectring only countries with distinct code (e.g. distinct countries) -->
            <xsl:apply-templates select="/aid/country[generate-id()
                                                        =
                                                        generate-id(key('kCountry', @code)[1])
                                                        ]"/>
        </aid>
    </xsl:template>
    
    <xsl:template match="country">
        <!-- pasting of name and all transactions (TWB and UNDP) for selected country -->       
        <xsl:variable name="code" select="./@code"/>
        
        <country code="{$code}">
            <xsl:apply-templates select="./name" mode="copy"/>
            <xsl:apply-templates select="/aid/country[./@code=$code]/transaction" mode="copy"/>                    
        </country>
    </xsl:template>

    <!-- templates for coping elements without namespace="" -->
    <xsl:template match="*" mode="copy">
        <xsl:element name="{name()}">
            <xsl:apply-templates select="@*|node()" mode="copy" />
        </xsl:element>
    </xsl:template>

    <!-- copy attributes, text nodes and comments -->
    <xsl:template match="@*|text()|comment()" mode="copy">
        <xsl:copy/>
    </xsl:template>
    
</xsl:stylesheet>
